import { Component } from '@angular/core';
import { Platform, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { RestService } from '../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { LoginPage } from '../pages/login/login';
import { PersonPage } from '../pages/person/person'


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage: any;

  constructor(platform: Platform,
              private statusBar: StatusBar,
              private splashScreen: SplashScreen,
              private events: Events,
              private translate: TranslateService,
              private rest: RestService) {
    platform.ready().then(() => {
      const user = this.rest.getUser();

      this.translate.addLangs(['zh', 'tw', 'en']);
      this.translate.setDefaultLang('en');

      let language = this.rest.getLanguage();
      if (!language) {
        switch (user.locale) {
        case 'en':
          this.translate.use('en');
          break;
        case 'zh-CN':
          this.translate.use('zh');
          break;
        case 'zh-TW':
          this.translate.use('tw');
          break;
        default:
          console.info('Use browser settings to set locale.');
          const browserLang = this.translate.getBrowserLang();
          this.translate.use(browserLang.match(/zh|en/) ? browserLang : 'zh');
          break;
        }
      } else {
        console.info('Use saved language: ' + language);
        this.translate.use(language);
      }

      if (!this.rest.doLoginFlag) {
        this.rootPage = PersonPage;
        this.appReady();
        return;
      }

      this.events.subscribe('token:failed', () => {
        this.rootPage = LoginPage;
      });

      if (user && user.username && user.role && user.password) {
        this.rest.getTokenFromServer({
          grant_type: 'password',
          username: user.username,
          password: user.password,
          client_id: 'webmobile',
        }, data => {
          const token = data['access_token'];
          this.rest.saveToken(token);
          const refreshToken = data['refresh_token'];
          this.rest.saveRefreshToken(refreshToken);
          this.rootPage = PersonPage;
          this.appReady();
        }, () => {
          this.rootPage = LoginPage;
          this.appReady();
        });
      } else {
        this.rootPage = LoginPage;
        this.appReady();
      }
    });
  }

  appReady() {
    this.statusBar.styleDefault();
    this.statusBar.overlaysWebView(false);
    this.splashScreen.hide();
  }
}
